<template>
	<section>
		<el-row>
			<el-col :span="5">
				<ad-position-mng @row-click="positionRowClick" :simple="true" @location-change="changeShopLocation"></ad-position-mng>
			</el-col>
			<el-col :span="19" class="app-container">
				<el-row >
<!--         	<el-button @click="showSelectShopMethod"  icon="el-icon-location-outline">{{userInfo.locationName}} <span style="color:blue;">切换店铺</span></el-button>-->

					<el-input v-model="filters.key" style="width:20%;" placeholder="模糊查询"></el-input>
					<el-button type="primary" v-on:click="searchAds" icon="el-icon-search">查询</el-button>
          <el-date-picker v-model="filters.dateKey" align="right" type="date" placeholder="选择到期日期" :picker-options="pickerOptions"
                          value-format="yyyy-MM-dd" format="yyyy-MM-dd" @change="searchAdsByDate"></el-date-picker>
					<el-button type="primary" @click="showAdd" icon="el-icon-plus"></el-button>
					<el-button type="danger" @click="batchDel" :disabled="this.sels.length===0" icon="el-icon-delete"></el-button>
				</el-row>
				<el-row style="padding-top:12px;">
					<!--列表 Ad pub_ad-->
          <el-table ref="ad" :data="adverts" :height="maxTableHeight" @sort-change="sortChange" highlight-current-row
                      v-loading="listLoading" border @selection-change="selsChange" @row-click="rowClick" style="width: 100%;">
            <el-table-column align="center" type="selection" width="55"></el-table-column>
						<el-table-column align="center" type="index" width="60"></el-table-column>
            <el-table-column align="center" prop="name" label="广告名称" min-width="80" show-overflow-tooltip></el-table-column>
            <el-table-column align="center" prop="positionId" label="广告位置" min-width="80" show-overflow-tooltip
                             :formatter="formatterPositionId"></el-table-column>
						<el-table-column align="center" prop="imageUrl" label="图片" min-width="120" show-overflow-tooltip>
							<template slot-scope="scope">
								<img :src="converUrl(scope.row.imageUrl)" style="max-width:100px;max-height:100px;">
							</template>
						</el-table-column>
						<!-- <el-table-column prop="link" label="跳转链接" min-width="80" show-overflow-tooltip></el-table-column> -->
            <el-table-column align="center" prop="startTime" label="开始时间" min-width="80" show-overflow-tooltip></el-table-column>
						<el-table-column align="center" prop="endTime" label="结束时间" min-width="80" show-overflow-tooltip></el-table-column>
						<el-table-column align="center" prop="enabled" label="上线/下线" min-width="80" show-overflow-tooltip>
              <template slot-scope="scope">
                <el-switch v-model="scope.row.enabled" active-value="1" inactive-value="0"
                           @change="updateAdvertInfo(scope.row)"> </el-switch>
              </template>
						</el-table-column>
            <el-table-column align="center" prop="sortOrder" label="顺序" min-width="60" show-overflow-tooltip></el-table-column>
            <el-table-column align="center" prop="clickNum" label="点击次数" min-width="80" show-overflow-tooltip></el-table-column>
            <el-table-column align="center" prop="saleNum" label="生成订单" min-width="80" show-overflow-tooltip></el-table-column>
						<el-table-column align="center" prop="isEnd" label="状态" min-width="80" show-overflow-tooltip>
							<template slot-scope="scope">
								<el-tag v-if="scope.row.isEnd=='1'" type="danger">结束</el-tag>
								<el-tag v-if="scope.row.isEnd=='0'" >未结束</el-tag>
							</template>
						</el-table-column>
						<!-- <el-table-column prop="imageUrl" label="图片链接" min-width="80" show-overflow-tooltip></el-table-column> -->
						<!-- <el-table-column prop="deptid" label="机构编号" min-width="80" show-overflow-tooltip></el-table-column> -->
						<!--<el-table-column prop="content" label="广告内容" min-width="80" show-overflow-tooltip></el-table-column>-->
						<el-table-column align="center" label="操作" min-width="150">
							<template slot-scope="scope">
								<el-button @click="showEdit( scope.row,scope.$index)">改</el-button>
								<el-button type="danger" @click="handleDel(scope.row,scope.$index)">删</el-button>
							</template>
						</el-table-column>
					</el-table>
					<el-pagination layout="total, sizes, prev, pager, next" @current-change="handleCurrentChange" @size-change="handleSizeChange"
					 :page-sizes="[10,20, 50, 100, 500]" :current-page.sync="pageInfo.pageNum" :page-size="pageInfo.pageSize" :total="pageInfo.total"
					 style="float:right;"></el-pagination>
				</el-row>
			</el-col>
			<!--编辑 Ad pub_ad界面-->
			<el-drawer title="编辑广告" :visible.sync="editFormVisible" size="50%" :close-on-click-modal="false">
				<ad-edit :ad="editForm" :ad-position="position" :visible="editFormVisible" :ad-location-id="chooseLocationId"  @cancel="editFormVisible=false"
				 @submit="afterEditSubmit"></ad-edit>
			</el-drawer>

			<!--新增 Ad pub_ad界面-->
			<el-drawer title="添加广告" :visible.sync="addFormVisible" append-to-body size="50%" :close-on-click-modal="false">
				<ad-add :ad="addForm" :ad-position="position" :visible="addFormVisible" :ad-location-id="chooseLocationId" @cancel="addFormVisible=false" @submit="afterAddSubmit"></ad-add>
			</el-drawer>
      <el-dialog title="选择商户" :visible.sync="selectShopVisible" width="70%" append-to-body>
      	<select-shop-location-by-sys-dept @sure="sureMethod"></select-shop-location-by-sys-dept>
      </el-dialog>
		</el-row>
	</section>
</template>

<script>
	import util from '@/common/js/util'; //全局公共库 
	import {listAdvert, delAdvert, batchDelAdvert,updateAdvertInfo} from '@/api/mdp/arc/ad/advert';
	import AdvertAdd from './AdvertAdd'; //新增界面
	import AdvertEdit from './AdvertEdit'; //修改界面
	import PositionMng from '../position/PositionMng'; //广告位置
	import Sticky from '@/components/Sticky' // 粘性header组件
	import {mapGetters} from 'vuex';

	export default {
		props: ['visible'],
		watch: {
			'visible': function(visible) {
				if (visible == true) {
					//从新打开页面时某些数据需要重新加载，可以在这里添加
					this.getAdverts();
				}
			},
		},
		data() {
			return {
				chooseLocationId:'',
				customerMyLocations: [],
				filters: {
					key: '',
					locationId: '',
					shopId: '',
          dateKey:''
				},
				listImg: [],
				adverts: [], //查询结果
				pageInfo: { //分页数据
					total: 0, //服务器端收到0时，会自动计算总记录数，如果上传>0的不自动计算。
					pageSize: 10, //每页数据
					pageNum: 1, //当前页码、从1开始计算
					orderFields: [], //排序列 如 ['sex','student_id']，必须为数据库字段
					orderDirs: [] //升序 asc,降序desc 如 性别 升序、学生编号降序 ['asc','desc']
				},
				listLoading: false, //查询中...
				sels: [], //列表选中数据
				options: {}, //下拉选择框的所有静态数据 options.sex,options.project

        addFormVisible: false,//新增ad界面是否显示
        //新增ad界面初始化数据
        addForm: {
          id:'',positionId:'',mediaType:'',name:'',link:'',endTime:'',enabled:'1',startTime:'',imageUrl:'',locationId:'',content:'',shopId:'',shareLvl:'',adType:'',clickNum:'',showNum:'',overTime:'',saleNum:'',sortOrder:'',showPct:'',remark:'',
          extraImage:'',goodsPrice:'',smallImage:''
        },

        editFormVisible: false,//编辑界面是否显示
        //编辑ad界面初始化数据
        editForm: {
          id:'',positionId:'',mediaType:'',name:'',link:'',endTime:'',enabled:'',startTime:'',imageUrl:'',locationId:'',content:'',shopId:'',shareLvl:'',adType:'',clickNum:'',showNum:'',overTime:'',saleNum:'',sortOrder:'',showPct:'',remark:'',
          extraImage:'',goodsPrice:'',smallImage:''
        },
        maxTableHeight:300,
				/**begin 自定义属性请在下面加 请加备注**/
				position: {},
        oneShopId:"", //暂时使用,只能选一个门店
        oneLocationId: "", //暂时使用,只能选一个门店
        oneLocationName:"",//暂时使用,只能选一个门店名字
        selectShopVisible: false,
        pickerOptions: {
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '三天内',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 3);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周内',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }]
        },
				/**end 自定义属性请在上面加 请加备注**/
			}
		}, //end data
		methods: {
      showSelectShopMethod() {
      	this.selectShopVisible = true;
      },
      sureMethod(row) {
      	this.selectShopVisible = false;
      	this.oneShopId = row.shopId;
      	this.chooseLocationId = row.id;
      	this.oneLocationName = row.businessName;
      	this.filters.locationId= row.id;
      },

			//获取代码对应的名称 用于数据反显 如 getCodeName(options.sex,'1');
			getCodeName(options, codeValue) {
				if (!options) return codeValue;
				let code = options.filter(i => i.codeValue == codeValue);
				if (code.length > 0) {
					return code[0].codeName
				} else {
					return codeValue
				}
			},
			handleSizeChange(pageSize) {
				this.pageInfo.pageSize = pageSize;
				this.pageInfo.count = true;

				this.getAdverts();
			},
			handleCurrentChange(pageNum) {
				this.pageInfo.pageNum = pageNum;
				this.getAdverts();
			},
			// 表格排序 obj.order=ascending/descending,需转化为 asc/desc ; obj.prop=表格中的排序字段,字段驼峰命名
			sortChange(obj) {
				var dir = 'asc';
				if (obj.order == 'ascending') {
					dir = 'asc'
				} else {
					dir = 'desc';
				}
				if (obj.prop == 'xxx') {
					this.pageInfo.orderFields = ['xxx'];
					this.pageInfo.orderDirs = [dir];
				}
				this.getAdverts();
			},
			searchAds() {

				this.pageInfo.count = true;
				this.getAdverts();
			},
			//获取列表 Ad pub_ad
			getAdverts() {
				let params = {
					pageSize: this.pageInfo.pageSize,
					pageNum: this.pageInfo.pageNum,
					total: this.pageInfo.total,
					count: this.pageInfo.count
				};
				if (this.pageInfo.orderFields != null && this.pageInfo.orderFields.length > 0) {
					let orderBys = [];
					for (var i = 0; i < this.pageInfo.orderFields.length; i++) {
						orderBys.push(this.pageInfo.orderFields[i] + " " + this.pageInfo.orderDirs[i])
					}
					params.orderBy = orderBys.join(",")
				}
				if (this.filters.key !== "") {
					params.key = "%" + this.filters.key + "%"
				}
        if (this.filters.dateKey !== "") {
          params.btime = util.formatDate(new Date(),"yyyy-MM-dd") ;//beginTime:筛选开始时间
          params.etime = this.filters.dateKey;//endTime:筛选结束时间
        }
				if (this.position && this.position.id != null && this.position.id != '') {
					params.positionId = this.position.id;
				}
				/* if (this.position.locationId == '' || this.position.locationId == null || this.position.shopId == '' || this.position
					.shopId == null) {
					this.$message.error("店铺编号不能为空，请选择位置")
					return
				} */
				/* params.locationId = this.position.locationId*/
				params.shopId = this.userInfo.shopId;
				if (this.position.posType == "0") {
					params.locationId = this.userInfo.shopId+'-0';
				} else {
					if(!this.chooseLocationId){
						return;
					}else{
						params.locationId=this.chooseLocationId;
					}
				};
				this.listLoading = true;
				listAdvert(params).then((res) => {
					var tips = res.data.tips;
					if (tips.isOk) {
						this.pageInfo.total = res.data.total;
						this.pageInfo.count = false;
						this.adverts = res.data.data;
					} else {
						this.$message({
							message: tips.msg,
							type: 'error'
						});
					}
					this.listLoading = false;
				}).catch(() => {
					this.listLoading = false;

				});
			},

			//显示编辑界面 Ad pub_ad
			showEdit: function(row, index) {
				this.editFormVisible = true;
				this.editForm = Object.assign({}, row);
			},
			//显示新增界面 Ad pub_ad
			showAdd: function() {
				if (this.position.id == '' || this.position.id == 'undefined' || this.position.id == null) {
					this.$message({
						message: '请先选择广告位置'
					});
					return false;
				}
				if(this.position.posType=='1'){
					if(!this.chooseLocationId){
						this.$message({
							message: '请选择某个门店'
						});
						return false;
					}
				}
				/*this.addForm.locationId = this.position.locationId;
				this.addForm.shopId = this.position.shopId;*/
				if(this.position.posType=='0'){
					this.addForm.locationId='0';
				}else{
					this.addForm.locationId=this.chooseLocationId;
				}
				this.addFormVisible = true;
				this.addForm.shopId = this.userInfo.shopId;

				this.addForm = Object.assign({}, this.addForm);
				//this.addFormVisible = true;
				//this.addForm=Object.assign({}, this.editForm);
			},
			afterAddSubmit() {
				this.addFormVisible = false;
				this.pageInfo.count = true;
				this.getAdverts();
			},
			afterEditSubmit() {
				this.editFormVisible = false;
				this.getAdverts();
			},
			//选择行ad
			selsChange: function(sels) {
				this.sels = sels;
				this.listImg = sels;
			},
			//删除ad
			handleDel: function(row, index) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					let params = {
						id: row.id
					};
					delAdvert(params).then((res) => {
						this.listLoading = false;
						var tips = res.data.tips;
						if (tips.isOk) {
							this.pageInfo.count = true;
							this.getAdverts();
						}
						this.$message({
							message: tips.msg,
							type: tips.isOk ? 'success' : 'error'
						});

					});
				}).catch(() => {
					this.listLoading = false;

				});
			},
			//批量删除ad
			batchDel: function() {
				var ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					batchDelAdvert(ids).then((res) => {
						this.listLoading = false;
						var tips = res.data.tips;
						if (tips.isOk) {
							this.pageInfo.count = true;
							this.getAdverts();
						}
						this.$message({
							message: tips.msg,
							type: tips.isOk ? 'success' : 'error'
						});
					});
				}).catch(() => {
					this.listLoading = false;

				});
			},
			rowClick: function(row, event, column) {
				this.$emit('row-click', row, event, column); //  @row-click="rowClick"
			},
			/**begin 自定义函数请在下面加**/
			positionRowClick: function(row, event, column) {
				this.pageInfo.count = true;
				this.position = row;
				this.chooseLocationId='';
				this.addForm.locationName='';
				this.adverts = [];
				this.getAdverts();
			},
			formatterPositionId: function() {
				return this.position.name
			},
			formatterYesOrNo: function(row, column, cellValue, index) {
				return cellValue == '1' ? '√' : 'X'
			},
			converUrl(url) {
				if (url == null || url == '' || url == 'undefined') {
					return url;
				}
				if (!url.indexOf('http') == 0 && !url.indexOf('www') == 0) {
					return "/arc/" + url;
				}
				return url;
			},
			changeShopLocation(locationId) {
				this.adverts = []
				this.customerMyLocations.some(i => {
					if (i.locationId == locationId) {
						this.addForm.locationId = i.locationId;
						this.addForm.locationName = i.locationName;
						this.addForm.shopId = i.shopId;
						this.filters.locationId = i.locationId
						this.filters.shopId = i.shopId
						this.chooseLocationId=locationId;
						//this.searchAds()
						this.getAdverts();
						return true;
					}
				});
			},
			getAllLocationByShopIdMethod() {
				let params = {};
				params.shopId = this.userInfo.shopId;
				//params.shopId = '2018081600000001';
				getAllLocationByShopIdApi(params).then((res) => {
					var tips = res.data.tips; //获取饭回来的数据
					if (tips.isOk) {
						for (let i = 0; i < res.data.data.length; i++) {
							if(res.data.data[i].locationid=='0'){
								continue;
							}
							let p = {
								"locationId": res.data.data[i].locationid,
								"locationName": res.data.data[i].locationname,
							}
							this.customerMyLocations.push(p);
						}
						this.changeShopLocation(this.userInfo.locationId);
					} else {
						this.$message({
							message: tips.msg,
							type: 'error'
						});
					}
				});
			},
      searchAdsByDate(){
			  this.getAdverts();
      },
      getLocationAndShop(){
        this.addForm.locationId = this.userInfo.locationId;
        this.addForm.locationName = this.userInfo.locationName;
        this.addForm.shopId = this.userInfo.shopId;
        this.filters.locationId = this.userInfo.locationId
        this.filters.shopId = this.userInfo.shopId
        this.chooseLocationId=this.userInfo.locationId;
        this.getAdverts();
      },
      /**end 自定义函数请在上面加**/
      updateAdvertInfo(row){
        let params={
          id:row.id,
          enabled:row.enabled
        }
        this.listLoading = true;
        updateAdvertInfo(params).then( (res) => {
            this.listLoading = false;
            let tips=res.data.tips;
            if(tips.isOk){
              this.getAdverts();
            }
        }).catch(() => {
            this.listLoading = false;
        });
      }
		}, //end methods
		components: {
			'ad-add': AdvertAdd,
			'ad-edit': AdvertEdit,
			'ad-position-mng': PositionMng, 
			'sticky': Sticky
			//在下面添加其它组件
		},
		computed: {
			...mapGetters([
				'roles', 'userInfo', 'myShops', 'myLocations'
			])
		},
		mounted() {
			this.$nextTick(() => {
				//this.getAdverts();
				this.getLocationAndShop();
        var clientRect=this.$refs.ad.$el.getBoundingClientRect();
        var subHeight=70/1000 * window.innerHeight;
        this.maxTableHeight =  window.innerHeight -clientRect.y - this.$refs.ad.$el.offsetTop-subHeight;
			});
		}
	}
</script>

<style scoped>

</style>
